<html><head><meta charset="utf-8"><title> 16 Webpack 环境相关配置及配置文件拆分-慕课专栏</title>
			<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
			<meta name="renderer" content="webkit">
			<meta property="qc:admins" content="77103107776157736375">
			<meta property="wb:webmaster" content="c4f857219bfae3cb">
			<meta http-equiv="Access-Control-Allow-Origin" content="*">
			<meta http-equiv="Cache-Control" content="no-transform ">
			<meta http-equiv="Cache-Control" content="no-siteapp">
			<link rel="apple-touch-icon" sizes="76x76" href="https://www.imooc.com/static/img/common/touch-icon-ipad.png">
			<link rel="apple-touch-icon" sizes="120x120" href="https://www.imooc.com/static/img/common/touch-icon-iphone-retina.png">
			<link rel="apple-touch-icon" sizes="152x152" href="https://www.imooc.com/static/img/common/touch-icon-ipad-retina.png">
			<link href="https://moco.imooc.com/captcha/style/captcha.min.css" rel="stylesheet">
			<link rel="stylesheet" href="https://www.imooc.com/static/moco/v1.0/dist/css/moco.min.css?t=201907021539" type="text/css">
			<link rel="stylesheet" href="https://www.imooc.com/static/lib/swiper/swiper-3.4.2.min.css?t=201907021539">
			<link rel="stylesheet" href="https://static.mukewang.com/static/css/??base.css,common/common-less.css?t=2.5,column/zhuanlanChapter-less.css?t=2.5,course/inc/course_tipoff-less.css?t=2.5?v=201907051055" type="text/css">
			<link charset="utf-8" rel="stylesheet" href="https://www.imooc.com/static/lib/ueditor/themes/imooc/css/ueditor.css?v=201907021539"><link rel="stylesheet" href="https://www.imooc.com/static/lib/baiduShare/api/css/share_style0_16.css?v=6aba13f0.css"></head>
			<body><div id="main">

<div class="container clearfix" id="top" style="display: block; width: 1134px;">
    
    <div class="center_con js-center_con l" style="width: 1134px;">
        <div class="article-con">
                            <!-- 买过的阅读 -->
                <div class="map">
                    <a href="/read" target="_blank"><i class="imv2-feather-o"></i></a>
                    <a href="/read/29" target="_blank">Webpack 从零入门到工程化实战</a>
                    <a href="" target="_blank">
                        <span>
                            / 2-10  16 Webpack 环境相关配置及配置文件拆分
                        </span>
                    </a>
                </div>

            


            <div class="art-title" style="margin-top: 0px;">
                 16 Webpack 环境相关配置及配置文件拆分
            </div>
            <div class="art-info">
                
                <span>
                    更新时间：2019-06-24 09:30:10
                </span>
            </div>
            <div class="art-top">
                                <img src="https://img1.mukewang.com/5cd963cd0001682f06400359.jpg" alt="">
                                                <div class="famous-word-box">
                    <img src="https://www.imooc.com/static/img/column/bg-l.png" alt="" class="bg1 bg">
                    <img src="https://www.imooc.com/static/img/column/bg-r.png" alt="" class="bg2 bg">
                    <div class="famous-word">最聪明的人是最不愿浪费时间的人。<p class="author">——但丁</p></div>
                </div>
                            </div>
            <div class="art-content js-lookimg">
                <div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在实际开发实践中，为了方便开发调试和上线，项目中我们一般配置两个 Webpack 配置，一个是<strong>开发环境</strong>一个是<strong>生产环境</strong>，开发环境帮助我们快速开发测试联调，生产环境保证上线环境的打包流程是最优化体验，这就是配置文件根据环境进行拆分。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">配置文件拆分最重要的收益是我们可以提取不同目标之间的共性，将经常改动的配置跟公共配置分开。并且还可以识别要组合的较小配置部件，这些配置不仅可以推送到自己的软件包以跨项目使用。另外，配置拆分还可以将配置作为依赖项进行管理，而不是在多个项目中复制类似的配置。</p>
</div><div class="cl-preview-section"><h2 id="开发环境和生产环境需要注意的区别" style="font-size: 30px;">开发环境和生产环境需要注意的区别</h2>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;">生产环境可能需要分离 CSS 成单独的文件，以便多个页面共享同一个 CSS 文件；</li>
<li style="font-size: 20px; line-height: 38px;">生产环境需要压缩 HTML/CSS/JS 代码；</li>
<li style="font-size: 20px; line-height: 38px;">生产环境需要压缩图片；</li>
<li style="font-size: 20px; line-height: 38px;">开发环境需要生成 SourceMap 文件；</li>
<li style="font-size: 20px; line-height: 38px;">开发环境需要打印 debug 信息；</li>
<li style="font-size: 20px; line-height: 38px;">开发环境需要 HMR、devServer 等功能…</li>
</ul>
</div><div class="cl-preview-section"><h2 id="按环境划分-webpack-配置文件" style="font-size: 30px;">按环境划分 Webpack 配置文件</h2>
</div><div class="cl-preview-section"><ul>
<li style="font-size: 20px; line-height: 38px;"><code>webpack.config.js</code>：所有环境的默认入口配置文件；</li>
<li style="font-size: 20px; line-height: 38px;"><code>webpack.base.js</code>：基础部分，即多个文件中共享的配置；</li>
<li style="font-size: 20px; line-height: 38px;"><code>webpack.development.js</code>：开发环境使用的配置；</li>
<li style="font-size: 20px; line-height: 38px;"><code>webpack.production.js</code>：生产环境使用的配置。</li>
</ul>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// webpack.config.js</span>
<span class="token keyword">const</span> baseWebpackConfig <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'./webpack.base.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> devWebpackConfig <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'./webpack.development.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> merge <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'webpack-merge'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token function">merge</span><span class="token punctuation">(</span>baseWebpackConfig<span class="token punctuation">,</span> devWebpackConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="webpack-development-config">webpack development config</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>webpack.development.js</code>文件里面的配置多数跟开发环境相关的配置，例如<code>devServer</code>和一些开发环境中需要的 plugin，比如 hmr、devServer、devtool 等。</p>
</div><div class="cl-preview-section"><h3 id="webpack-production-config">webpack production config</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">这里的配置主要包括了跟生产环境相关的配置项，例如<code>optimization</code>、<code>devtool</code>等。</p>
</div><div class="cl-preview-section"><h3 id="webpack-base-config">webpack base config</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;"><code>webpack.base.js</code>是公共部分的配置，除了完全一致的内容之外，还可能会涉及到一些根据不同环境做的事情，比如 <code>style-loader</code>在开发环境用，而开发环境是用<code>mini-css-extract-plugin</code>的 loader，这时候需要使用环境变量来判断。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">有两种方式来判断当前的环境变量：</p>
</div><div class="cl-preview-section"><ol>
<li style="font-size: 20px; line-height: 38px;">使用环境变量，例如 <a href="https://www.npmjs.com/package/cross-env">cross-env</a> + <code>NODE_ENV</code>;</li>
<li style="font-size: 20px; line-height: 38px;">使用 Webpack 配置文件的<code>function</code> 方式。</li>
</ol>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">Tips：这是因为我们所有的入口文件都是<code>webpack.config.js</code>。当然如果我们使用 Webpack 的时候，就已经在<code>npm scripts</code>里面区分了配置文件（<code>webpack --config webpack.production.js</code>），就不在讨论范围之内了。这里只是顺着之前的逻辑继续分析下去。</p>
</blockquote>
</div><div class="cl-preview-section"><h3 id="cross-env">cross-env</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先安装 <a href="https://www.npmjs.com/package/cross-env">cross-env</a>：</p>
</div><div class="cl-preview-section"><pre class="  language-bash"><code class="prism  language-bash"><span class="token function">npm</span> i -D cross-env
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后修改<code>npm scripts</code>内容：</p>
</div><div class="cl-preview-section"><pre class="  language-json"><code class="prism  language-json"><span class="token comment">// package.json</span>
<span class="token punctuation">{</span>
    <span class="token string">"scripts"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
        <span class="token string">"build"</span><span class="token punctuation">:</span> <span class="token string">"cross-env NODE_ENV=production webpack --config webpack.config.js"</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">最后在<code>webpack.base.js</code>中使用环境变量：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// webpack.base.js</span>
<span class="token keyword">const</span> isProduction <span class="token operator">=</span> process<span class="token punctuation">.</span>env<span class="token punctuation">.</span>NODE_ENV <span class="token operator">===</span> <span class="token string">'production'</span><span class="token punctuation">;</span>
<span class="token comment">//....</span>
module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    <span class="token comment">// ...</span>
    devtool<span class="token punctuation">:</span> isProduction <span class="token operator">?</span> <span class="token keyword">null</span> <span class="token punctuation">:</span> <span class="token string">'source-map'</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h3 id="function配置"><code>function</code>配置</h3>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">根据前面的章节我们知道，Webpack 的配置可以是对象，也可以是函数，如果是 function 则接受一个<code>mode</code>参数，即开发环境打包还是生产环境打包。利用这一点我们可以做下面的配置。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">首先是修改<code>npm scripts</code>添加<code>--mode</code>选项：</p>
</div><div class="cl-preview-section"><pre class="  language-json"><code class="prism  language-json"><span class="token comment">// package.json</span>
<span class="token punctuation">{</span>
    <span class="token string">"scripts"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>
        <span class="token string">"build"</span><span class="token punctuation">:</span> <span class="token string">"webpack --mode production --config webpack.config.js"</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">然后我们可以将配置文件改成 function 类型的配置：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// 以webpack.config.js为例</span>
module<span class="token punctuation">.</span><span class="token function-variable function">exports</span> <span class="token operator">=</span> mode <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>mode <span class="token operator">===</span> <span class="token string">'production'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 生产环境</span>
    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
        <span class="token comment">// 开发环境</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h2 id="将零件配置进行拆分" style="font-size: 30px;">将零件配置进行拆分</h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">除了按照开发环境拆分出<code>development</code>和<code>production</code>之外，我们还可以将公共的配置按照 loader、devServer 等相关配置拆到<code>webpack.parts.js</code>文件中，在其他项目直接组装想用的内容即可。</p>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">例如下面的配置：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token comment">// webpack.parts.js</span>
<span class="token keyword">const</span> MiniCssExtractPlugin <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'mini-css-extract-plugin'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

<span class="token comment">// 获取 css-loader 配置</span>
exports<span class="token punctuation">.</span>getCssLoader <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>mode<span class="token punctuation">,</span> test <span class="token operator">=</span> <span class="token regex">/\.css$/</span><span class="token punctuation">,</span> include<span class="token punctuation">,</span> exclude<span class="token punctuation">,</span> uses <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>
    test<span class="token punctuation">,</span>
    include<span class="token punctuation">,</span>
    exclude<span class="token punctuation">,</span>
    use<span class="token punctuation">:</span> <span class="token punctuation">[</span>
        <span class="token punctuation">{</span>
            loader<span class="token punctuation">:</span> mode <span class="token operator">===</span> <span class="token string">'production'</span> <span class="token operator">?</span> MiniCssExtractPlugin<span class="token punctuation">.</span>loader <span class="token punctuation">:</span> <span class="token string">'style-loader'</span>
        <span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token punctuation">{</span>
            loader<span class="token punctuation">:</span> <span class="token string">'css-loader'</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>uses<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 获取 devServer 配置</span>
exports<span class="token punctuation">.</span>getDevServerConfig <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>host <span class="token operator">=</span> <span class="token string">'0.0.0.0'</span><span class="token punctuation">,</span> port <span class="token operator">=</span> <span class="token number">8888</span><span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>
    stats<span class="token punctuation">:</span> <span class="token string">'errors-only'</span><span class="token punctuation">,</span>
    host<span class="token punctuation">,</span>
    port<span class="token punctuation">,</span>
    open<span class="token punctuation">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
    overlay<span class="token punctuation">:</span> <span class="token boolean">true</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// 获取 url-loader 配置</span>
exports<span class="token punctuation">.</span><span class="token function-variable function">getUrlLoader</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>test<span class="token punctuation">,</span> largeAssetSize <span class="token operator">=</span> <span class="token number">1000</span><span class="token punctuation">,</span> assetsDir<span class="token punctuation">,</span> dir<span class="token punctuation">}</span> <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">(</span><span class="token punctuation">{</span>
    test<span class="token punctuation">,</span>
    use<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        loader<span class="token punctuation">:</span> <span class="token string">'url-loader'</span><span class="token punctuation">,</span>
        options<span class="token punctuation">:</span> <span class="token punctuation">{</span>
            limit<span class="token punctuation">:</span> largeAssetSize<span class="token punctuation">,</span>
            name<span class="token punctuation">:</span> <span class="token function">getAssetPath</span><span class="token punctuation">(</span>assetsDir<span class="token punctuation">,</span> <span class="token template-string"><span class="token string">`</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>dir<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">/[name]</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>isProduction <span class="token operator">?</span> <span class="token string">'.[hash:8]'</span> <span class="token punctuation">:</span> <span class="token string">''</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">.[ext]`</span></span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// .....</span>
</code></pre>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">使用的时候，直接调用对应的方法即可：</p>
</div><div class="cl-preview-section"><pre class="  language-js"><code class="prism  language-js"><span class="token keyword">const</span> partsConfig <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'./webpack.parts.js'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

module<span class="token punctuation">.</span>exports <span class="token operator">=</span> <span class="token punctuation">{</span>
    mode<span class="token punctuation">:</span> <span class="token string">'production'</span><span class="token punctuation">,</span>
    devtool<span class="token punctuation">:</span> <span class="token string">'source-map'</span><span class="token punctuation">,</span>
    <span class="token comment">//...</span>
    devServer<span class="token punctuation">:</span> partsConfig<span class="token punctuation">.</span><span class="token function">getDevServer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
    modules<span class="token punctuation">:</span> <span class="token punctuation">{</span>
        rules<span class="token punctuation">:</span> <span class="token punctuation">[</span>
            partsConfig<span class="token punctuation">.</span><span class="token function">getCssLoader</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            partsConfig<span class="token punctuation">.</span><span class="token function">getUrlLoader</span><span class="token punctuation">(</span><span class="token punctuation">{</span>test<span class="token punctuation">:</span> <span class="token regex">/\.(png|jpe?g|gif|webp|svg)(\?.*)?$/</span><span class="token punctuation">,</span> dir<span class="token punctuation">:</span> <span class="token string">'img'</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
            <span class="token comment">// ....</span>
        <span class="token punctuation">]</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
</div><div class="cl-preview-section"><h2 id="title小结---" style="font-size: 30px;"><div class="summary"><h5 class="centertitle" style="font-size: 20px; line-height: 38px;">小结 </h5></div><!--title:&#23567;&#32467; --></h2>
</div><div class="cl-preview-section"><p style="font-size: 20px; line-height: 38px;">在一个 Webpack 项目中，根据不同的使用环境合理划分 Webpack 的配置文件是很有必要的。本文介绍了如何按照开发环境和生产环境划分 Webpack 配置文件，并且介绍了公共配置部分拆分规则，可以使用 cross-env 模块来传入不同的环境变量，这样在公共配置文件内可以根据不同的环境变量进行配置。我们甚至可以将 Webpack 的配置拆成一个个的零件进行自由的搭配。</p>
</div><div class="cl-preview-section"><blockquote>
<p style="font-size: 20px; line-height: 38px;">本小节 Webpack 相关面试题：</p>
<ol>
<li style="font-size: 20px; line-height: 38px;">你们项目是如何管理 Webpack 的配置文件的？</li>
</ol>
</blockquote>
</div></div>
            </div>
                            <!-- 买过的阅读 -->
                <div class="art-next-prev clearfix">
                                                                        <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/273">
                                                    <div class="prev l clearfix">
                                <div class="icon l">
                                    <i class="imv2-arrow3_l"></i>
                                </div>
                                <p>
                                    15 Webpack 中配置React和Vue开发环境
                                </p>
                            </div>
                        </a>
                                                                                            <!-- 已买且开放 或者可以试读 -->
                            <a href="/read/29/article/275">
                                                    <div class="next r clearfix">
                                <p>
                                     17 Webpack 优化之体积优化
                                </p>
                                <div class="icon r">
                                    <i class="imv2-arrow3_r"></i>
                                </div>

                            </div>
                        </a>
                                    </div>
                    </div>
        <div class="comments-con js-comments-con" id="coments_con">
        </div>



    </div>
    
    
    

</div>
 
<!-- 专栏介绍页专栏评价 -->

<!-- 专栏介绍页底部三条评价 -->

<!-- 专栏阅读页弹层目录和介绍页页面目录 -->

<!-- 专栏阅读页发布回复 -->

<!-- 专栏阅读页发布评论 -->

<!-- 专栏阅读页底部评论 -->

<!-- 专栏阅读 单个 评论 -->

<!-- 新增回复和展开三条以外回复 -->

<!-- 立即订阅的弹窗 -->












</div></body></html>